
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb.Classes;
using jQueryApi;

namespace ThisILove
{
    public static class WordList
    {
        private static string _word;

        [PreserveName, PreserveCase]
        public static void EntryPage()
        {
            Inform.Debug("WordList.Page()");
            jQuery.Document.Unbind(".wordlist");
            jQuery.Document.Bind("OnPageSave.wordlist", SaveList);
        }

        [PreserveName, PreserveCase]
        public static void Widget()
        {
            PresentWord();
        }

        public static string Word
        {
            get
            {
                if (string.IsNullOrEmpty(_word))
                    PresentWord();
                return _word;
            }
        }

        public static void PresentWord()
        {
            const string wordList = "#WordList";
            new Await()
                .LoadJson(wordList, Uri.DbPath("wordlist.txt"))
                .AddDx(
                delegate
                {
                    List<string> words = (List<string>) Await.Files[wordList];
                    _word = words[Formulas.RandomOf(words.Count)];

                    jQueryObject el = jQuery.Select(wordList);
                    el.Html(_word);
                })
                .Commit();
        }

        [AlternateSignature]
        public static extern void SaveList(jQueryEvent e);

        public static void SaveList(jQueryEvent e, object arg)
        {
            List<string> words = new List<string>();
            jQueryObject el = jQuery.Select("#WordList");
            jQueryObject ls = jQuery.Select("li", el);

            ls.Each(
                delegate(int i, Element domEl)
                {
                    jQueryObject t = jQuery.FromElement(domEl);
                    words.Add(t.GetText().Trim());
                }
                );

            FileBlobBase.StoreBlobAw(Await.AsyncAw, "db", "wordlist", DomElement.ResultRx, words);
        }
    }
}
